<template>
  <n-modal v-model:show="visible" :title="title" display-directive="if" :bordered="false" preset="card" class="w-500px"
    size="huge" :closable="false">
    <n-form ref="formRef" :model="formData" :label-width="80" :rules="rules" label-placement="left">
      <n-grid x-gap="12" :cols="24">
        <n-form-item-gi :span="12" label="名字" path="name" class="fi-w">
          <n-input v-model:value="formData.name" :disabled="false" clearable />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="配置" path="value" class="fi-w">
          <n-input v-model:value="formData.value" :disabled="false" clearable />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="分组" path="group" class="fi-w">
          <n-input v-model:value="formData.configGroup" :disabled="false" clearable />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="类型" path="type" class="fi-w">
          <n-select v-model:value="formData.type" :disabled="false" :options="typeOptions" clearable />
        </n-form-item-gi>
        <n-form-item-gi :span="24" label="备注" path="remark" class="fi-w">
          <n-input type="textarea" v-model:value="formData.remark" :disabled="false" clearable />
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <n-space justify="center">
      <n-button @click="handleSubmitForm">确定</n-button>
      <n-button @click="handleCloseModal">取消</n-button>
    </n-space>
  </n-modal>
</template>

<script setup lang='ts'>
import { computed, ref, watch } from 'vue';
import { fetchAddConfig, fetchUpdateConfig, fetchConfig } from '@/service/api/sys/config'
import { Config,typeOptions } from "./index"
import { FlatResponseData } from '~/packages/axios/src/type';
import { useNaiveForm } from '@/hooks/common/form';

interface DataSource extends Config { }

type Props = {
  visible: boolean,
  operateType: NaiveUI.TableOperateType,
  editKey?: Common.IdType | null
}
const props = defineProps<Props>()
const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增',
    edit: '编辑'
  };
  return titles[props.operateType];
});
const editKey = computed(() => props.editKey || null);
interface Emits {
  (e: 'submitted'): void;
}
const emit = defineEmits<Emits>();

const formData = ref<DataSource>(initFormData());
const { formRef, validate, restoreValidation } = useNaiveForm();

const rules = {
  name: [
    { required: true, message: "名字不能为空", trigger: "blur" }
  ],
  value: [
    { required: true, message: "值不能为空", trigger: "blur" }
  ],
  type: [
    { required: true, message: "类型不能为空", trigger: "change" }
  ],
}

function initFormData(): DataSource {
  return {}
}

function handleCloseModal() {
  visible.value = false;
  emit("submitted")
}

function handleFetchResult(res: FlatResponseData<any, App.Service.Response<unknown>>) {
  if (!res.error) {
    window.$message?.success("操作成功");
    handleCloseModal()
  }
}

async function handleSubmitForm() {
  await validate()
  const value = formData.value
  if (value.id) {
    fetchUpdateConfig(formData.value).then(handleFetchResult)
  } else {
    fetchAddConfig(formData.value).then(handleFetchResult)
  }
}

async function initEditData() {
  if (props.operateType === 'edit' && editKey.value !== null) {
    const { data } = await fetchConfig(editKey.value)
    formData.value = data!;
  }
}

watch(visible, () => {
  if (visible.value) {
    restoreValidation()
    initEditData();
  } else {
    formData.value = initFormData()
  }
});

</script>

<style lang='scss' scoped></style>
